#!/usr/bin/env ruby
require 'rubygems'
require 'socket'
require 'optparse'
require 'pp'
require 'inifile'
require 'eventmachine'
require 'rexml/document'
include REXML

options = {}

optparse = OptionParser.new do |opts|
	opts.banner = "Usage: #{$0} [options] port"
	options[:config] = 'server.ini'
	options[:logfile] = 'log.txt'
	opts.on('-l', '--logfile FILE', 'log file location') do |file|
		options[:logfile] = file
	end
	opts.on('-c', '--config FILE', 'INI config file') do |file|
		options[:config] = file
	end
	opts.on('-h', '--help', 'Display this screen') do
		puts opts
		exit
	end

end

begin
	optparse.parse!
rescue OptionParser::InvalidOption => e
	puts e
	puts optparse
	exit
end

begin
	ini = IniFile.new options[:config], :parameter => '='
	print ini['src']['ip'], ':', ini['src']['port'], "\n"
	print ini['dst']['ip'], ':', ini['dst']['port'], "\n"
	#ini.write
rescue 
	print 'error: ', $!, '\n'
end

#ini = {'src'=>{'ip'=>'127.0.0.1','port'=>'2000'},'dst'=>{'ip'=>'127.0.0.1','port'=>'3000'}}

module PortListener
	def receive_data(data)
		send_data(data)
	end
end

EventMachine::run do
	EventMachine::start_server ini['src']['ip'], ini['src']['port'], PortListener
	puts "Started PortListener on #{ini['src']['ip']}:#{ini['src']['port']}"
end
=begin
server = TCPServer.new(ini['src']['ip'], ini['src']['port'])
while (session = server.accept)
	Thread.start do
		puts "log: Connection from #{session.peeraddr[2]} at #{session.peeraddr[3]}"
		#puts "log: got input from client"
		input = session.gets(sep="\r\n\r\n")
		puts input.chop!
		#session.puts "Server: Welcome #{session.peeraddr[2]}\n"

		xmldoc = Document.new input
		value = XPath.first xmldoc, "//Side/Count/text()"
		puts "==>#{value}"

		Thread.start do
			dest = TCPSocket.open(ini['dst']['ip'], ini['dst']['port']) rescue false
			if dest
				dest.send "#{value}\r\n\r\n"
				dest.close
			end
		end
				
		puts "log: sending goodbye"
		#session.puts "Server: Goodbye\n"
		session.close
	end
end
=end

# http://www.thebuzzmedia.com/programming-a-simple-clientserver-with-ruby/
# http://www.snowfrog.net/2009/10/02/ruby-argv-options-and-optionparser/
# http://ruby.about.com/od/advancedruby/a/optionparser.htm
#http://eric.lubow.org/2009/ruby/parsing-ini-files-with-ruby/
#http://snippets.dzone.com/posts/show/4918
#http://stackoverflow.com/questions/607640/how-to-read-an-ini-file-in-ruby
